<template>
  <div class="profile">
    <!-- 导航条 -->
    <van-nav-bar
      left-arrow
      @click-left="$router.back()"
      title="编辑资料"
    ></van-nav-bar>

    <!-- 编辑区 -->
    <van-cell-group>
      <!--头像区域-->
      <div class="avatar">
        <van-image
        fit="cover"
        round
        :src="user.photo"
         />
        <!-- 先导入并注册uploader组件-->
        <van-uploader
        class="upload"
        :after-read="afterRead"
        />
      </div>
      <van-cell
        is-link
        title="名称"
        :value="user.name"
        @click="showNameDialog"
      />
      <van-cell
        is-link
        title="性别"
        :value="gender"
        @click="showGender = true"
      />
      <van-cell is-link title="生日" :value="user.birthday" @click="showDate" />
    </van-cell-group>
    <van-dialog
      v-model="showName"
      title="修改用户名"
      show-cancel-button
      @confirm="saveName"
    >
      <van-field v-model.trim="userName" placeholder="请输入用户名" />
    </van-dialog>
    <van-popup v-model="showGender" position="bottom">
      <van-nav-bar
        title="修改性别"
        left-text="取消"
        @click-left="showGender = false"
      >
      </van-nav-bar>
      <van-cell title="男" @click="saveGender(0)" is-link></van-cell>
      <van-cell title="女" @click="saveGender(1)" is-link></van-cell>
    </van-popup>
    <van-popup v-model="showBirthday" position="bottom">
      <van-datetime-picker
        v-model="currentDate"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="saveBirthday"
      />
    </van-popup>
    <!-- 图片裁剪 -->
    <div class="mask" v-if="isShowMask">
    <VueCropper
        :img="img"
        autoCrop
        autoCropWidth="120"
        autoCropHeight="120"
        fixed
        ref="cropper"
        ></VueCropper>
    <van-button type="primary" class="confirm" @click="crop">
        确定
    </van-button>
    <van-button type="primary" class="cancel" @click="isShowMask = false"
        >取消</van-button
        >
</div>
  </div>
</template>

<script>
import { VueCropper } from 'vue-cropper'
import dayjs from 'dayjs'
import { reqGetProfile, reqUpdateUserInfo, reqUpdatePhoto } from '@/api/user'
export default {
  name: 'userProfile',
  data () {
    return {
      // 控制弹层
      showName: false,
      showGender: false,
      showBirthday: false,
      // 当前用户的信息
      user: {},
      userName: '',
      minDate: new Date('1950-1-1'),
      maxDate: new Date(),
      currentDate: new Date('2000-1-1'),
      isShowMask: false// 图片裁剪
    }
  },
  components: {
    VueCropper
  },
  created () {
    this.render()
  },
  computed: {
    gender () {
      return this.user.gender === 0 ? '男' : '女'
    }
  },
  methods: {
    async render () {
      const {
        data: { data }
      } = await reqGetProfile()
      this.user = data
    },
    showNameDialog () {
      this.showName = true
      this.userName = this.user.name
    },
    saveName () {
      if (this.userName.length < 1 || this.userName.length > 7) {
        return this.$toast.fail('请输入长度为1-7位')
      }
      try {
        reqUpdateUserInfo({ name: this.userName })
        this.render()
      } catch {
        this.$toast.fail('昵称已存在')
      }
    },
    saveGender (gender) {
      reqUpdateUserInfo({ gender })
      this.render()
      // 关闭弹层
      this.showGender = false
    },
    showDate () {
      this.showBirthday = true
      // this.user.birthday 是字符串 需要处理成时间对象
      this.currentDate = new Date(this.user.birthday)
    },
    async saveBirthday () {
      try {
        const birthday = dayjs(this.currentDate).format('YYYY-MM-DD')
        await reqUpdateUserInfo({
          birthday
        })
        // 更新视图
        this.render()
        this.$toast.success('修改成功')
        this.showBirthday = false
      } catch {
        this.$toast.fail('修改失败')
        this.showBirthday = false
      }
    },
    afterRead (file) {
      this.img = file.content // 上传的图片的地址
      this.isShowMask = true
    },
    crop () {
      this.$refs.cropper.getCropBlob(async data => {
        // do something
        const fm = new FormData()
        fm.append('photo', data)
        await reqUpdatePhoto(fm)
        this.$toast.success('上传成功')
        this.render()
        this.isShowMask = false
        // // 取fm中的值 两种方法
        // fm.get('photo')// 也可以使用getAll取所有的
        // for (const key in fm) {
        //   console.log(key)
        // }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .van-icon {
  color: #fff;
}
::v-deep .van-nav-bar__text {
  color: #fff;
}
.avatar {
  padding: 20px 0;
  text-align: center;
  position: relative;
  .van-image {
    width: 120px;
    height: 120px;
  }
  .upload {
    opacity: 0;
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    width: 120px;
    height: 120px;
    ::v-deep {
      .van-uploader__input {
        width: 120px;
        height: 120px;
      }
    }
  }
}
.profile {
  ::v-deep {
    .van-dialog__content {
      padding: 10px;
      .van-field {
        border: 1px solid #ccc;
      }
    }
  }
}
.mask {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 999;
  .confirm,
  .cancel {
    position: absolute;
    bottom: 0;
  }
  .confirm {
    left: 0;
  }
  .cancel {
    right: 0;
  }
}
</style>
